<template>
  <el-form ref="basicFormRef" class="w-160 ma-a pt-4" :model="basicForm" :rules="rules" size="small" label-width="80px">
    <el-form-item label="算法名称" prop="loadName">
      <el-input v-model="basicForm.algorithmName" placeholder="请输入" clearable :disabled="true" />
    </el-form-item>
    <el-form-item label="算法分类" prop="loadType">
      <el-select v-model="basicForm.loadType" clearable :disabled="true">
        <el-option v-for="(item, index) in pageLoadTypes" :key="'name' + index" :label="item.label" :value="item.label" />
      </el-select>
    </el-form-item>
    <el-form-item label="版本号" prop="version">
      <el-input v-model="basicForm.version" placeholder="请输入版本号" clearable :disabled="type === 'view'" />
    </el-form-item>
    <el-form-item label="算法实现" prop="stage">
      <div class="border-1 border-solid border-#e4e4e4 w-100%">
        <el-row :gutter="10">
          <el-col :span="14">
            <CodeEditor
              ref="codeEditorRef"
              v-model="basicForm.code"
              :readonly="type === 'view'"
              editor-id="codeEditor"
              @click="handleCodeEditorClick"
            />
            <!-- <el-input
              v-if="type === 'edit'"
              v-model="basicForm.version"
              class="pt-2 pl-2"
              placeholder="请输入"
              type="textarea"
              :autosize="{ minRows: 12, maxRows: 12 }"
              clearable
            />
            <el-input
              v-else
              v-model="basicForm.version"
              class="pt-2 pl-2 pb-2"
              placeholder="请输入"
              :disabled="type === 'view'"
              type="textarea"
              :autosize="{ minRows: 10 }"
              clearable
            /> -->
          </el-col>
          <el-col :span="10">
            <div class="font-size-3 pt-2">矩阵名称</div>
            <el-input v-model="basicForm.matrix" class="pt-2 pr-2" placeholder="请输入" :disabled="type === 'view'" clearable />
            <div class="font-size-3 pt-2">输入文件夹名称</div>
            <el-input v-model="basicForm.inputFolder" class="pt-2 pr-2" placeholder="请输入" :disabled="type === 'view'" clearable />
            <div class="font-size-3 pt-2">结果文件夹</div>
            <el-input v-model="basicForm.resultFolder" class="pt-2 pr-2" placeholder="请输入" :disabled="type === 'view'" clearable />
            <div v-if="type === 'edit'" class="mt-2 mb-2 pos-relative">
              <el-button size="small" type="primary" @click="handleDownload">下载</el-button>
              <el-upload
                v-model:file-list="fileList"
                class="upload-btn"
                :auto-upload="false"
                action="#"
                :accept="accept"
                :limit="1"
                :on-change="handleChange"
                :show-file-list="false"
              >
                <el-button type="primary">上传</el-button>
              </el-upload>
            </div>
          </el-col>
        </el-row>
        <div v-if="type === 'edit'" class="color-#f00 pl-2 font-size-3">注：1.修改算法内容时先下载，修改后重新上传,</div>
        <div v-if="type === 'edit'" class="color-#f00 pl-2 font-size-3">
          &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;2.如果矩阵及输入输出文件夹名称有修改时，先进行修改
        </div>
      </div>
    </el-form-item>
    <el-form-item label="更新人" prop="version">
      <span>{{ basicForm.version }}</span>
    </el-form-item>
    <el-form-item label="更新时间" prop="version">
      <span>{{ basicForm.version }}</span>
    </el-form-item>
    <el-form-item label="备注" prop="version">
      <el-input
        v-model="basicForm.version"
        placeholder="请输入版本号"
        type="textarea"
        :disabled="type === 'view'"
        :autosize="{ minRows: 2 }"
        clearable
      />
    </el-form-item>
    <el-dialog v-if="dialogVisiable" v-model="dialogVisiable" title="算法" width="80%">
      <CodeEditor v-model="codeValue" height="600px" editor-id="codeEditorDialog" :readonly="type === 'view'" />
      <template #footer>
        <div class="dialog-footer">
          <el-button v-if="type !== 'view'" type="primary" @click="handleSave">保存</el-button>
          <el-button @click="closeDialog">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </el-form>
</template>

<script setup name="AlgorithmDetailForm" lang="ts">
import { editAlgorithm, getAlgorithmDetail, downloadAlgorithmInfo } from '@/api/loadProcessingAlgorithm/loadAlgorithmManagement/index';
import { loadNames } from '@/api/loadProcessingAlgorithm/index';
import CodeEditor from './codeEditor.vue';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { dataId, type } = defineProps({
  dataId: String,
  type: String
});
const file = ref(null);
const basicFormRef = ref<ElFormInstance>();
const pageLoadNames = ref(loadNames);
const pageLoadTypes = ref([]);
const codeValue = ref('');
const basicForm = reactive({
  loadType: '',
  algorithmName: '',
  inputFolder: '',
  version: '',
  resultFolder: '',
  matrix: '',
  code: ''
});
const fileList = ref([]);
const accept = ref('.py');
const dialogVisiable = ref(false);
const codeEditorRef = ref();
const rules = reactive({
  loadType: [{ required: true, message: '分类不能为空', trigger: 'change' }],
  algorithmName: [{ required: true, message: '算法名称不能为空', trigger: 'change' }],
  inputolder: [{ required: true, message: '算法实现不能为空', trigger: 'change' }],
  inputFolder: [{ required: true, message: '模型范围不能为空', trigger: 'blur' }],
  resultFolder: [{ required: true, message: '结果文件不能为空', trigger: 'blur' }],
  matrix: [{ required: true, message: '矩阵名称不能为空', trigger: 'blur' }]
});
const submitData = async () => {
  if (!basicFormRef.value) return null;
  let data = null;
  await basicFormRef.value.validate(async (valid, fields) => {
    if (valid) {
      const res = await editAlgorithm(basicForm);
      data = res.data;
    }
  });
  return data;
};
const getLoadTypes = () => {
  pageLoadNames.value.forEach((item) => {
    pageLoadTypes.value = [...pageLoadTypes.value, ...item.children];
  });
};
const closeDialog = () => {
  dialogVisiable.value = false;
};
const handleSave = () => {
  basicForm.code = codeValue.value;
  codeEditorRef.value.setText(codeValue.value);
  const uint8Array = new TextEncoder().encode(codeValue.value);
  file.value = new Blob([uint8Array], { type: 'application/octet-stream' });
  dialogVisiable.value = false;
};
const handleCodeEditorClick = () => {
  codeValue.value = basicForm.code;
  dialogVisiable.value = true;
};
const getFileInfo = async () => {
  const formData = new FormData();
  formData.append('loadType', basicForm.loadType);
  formData.append('algorithmName', basicForm.algorithmName);
  file.value = await downloadAlgorithmInfo(formData);
  if (file.value) {
    const reader = new FileReader();
    reader.onload = function (e) {
      // 将文件内容设置到 CodeMirror 中
      basicForm.code = e.target.result;
    };
    reader.readAsText(file.value); // 以文本形式读取文件内容
  }
};
const downloadFile = (res, fileName) => {
  const blob = new Blob([res]);
  const objUrl = URL.createObjectURL(blob);
  const link = document.createElement('a');
  link.setAttribute('href', objUrl);
  link.setAttribute('download', fileName);
  link.style.display = 'none';
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
};
const handleDownload = () => {
  downloadFile(file.value, basicForm.algorithmName + '.py');
};
const handleChange = (file) => {
  if (file.status === 'ready') {
    const reader = new FileReader();
    reader.onload = function (e) {
      // 将文件内容设置到 CodeMirror 中
      basicForm.code = e.target.result;
      codeEditorRef.value.setText(basicForm.code);
    };
    reader.readAsText(file.raw); // 以文本形式读取文件内容
  }
};
defineExpose({
  submitData
});
onMounted(async () => {
  if (dataId) {
    const { data } = await getAlgorithmDetail(dataId);
    for (const key in basicForm) {
      basicForm[key] = data[key];
    }
    await getFileInfo();
  }
  getLoadTypes();
});
</script>
<style lang="scss" scoped>
.dialog-footer {
  text-align: center;
}
.upload-btn {
  position: absolute;
  left: 60px;
  top: 0px;
}
</style>
